
var express = require('express');
var router = express.Router();

var { user_model } = require("../utils/model")



// Vue3.0  项目的接口 
router.get("/test", (req, res) => {
  res.send("req")
})

// ajax 最好返回json 
router.all("/login", (req, res) => {
  var body = req.body;
  console.log(body);
  user_model.findOne({
    ...body
  })
    .then(result => {
      if (result) {
        res.json({
          code: 200,
          msg: '登陆成功',
          body,
          result
        })
      } else {
        res.json({
          code: 1001,
          msg: '登陆失败,账号或密码错误！',
        })
      }
    })
    .catch(err => {
      res.json({
        code: 500,
        msg: '服务器异常',
        err
      })
    })
})


router.all("/register", (req, res) => {
  var body = req.body;
  user_model.findOne({username:body.username}).then(result => {
      if (result) {
        res.json({
          code: 1001,
          msg: '账号已经被注册'
        })
      } else {
        user_model.insertMany(body).then(result => {
          if (result) {
            res.json({
              code: 200,
              msg: '注册成功',
              body,
              result
            })
          }
        })
      }
    })
    .catch(err => {
      res.json({
        code: 500,
        msg: '服务器异常',
        err
      })
    })
})


router.get("/userlist", (req, res) => {
  user_model.find()
    .then(result => {
      res.json({
        code: 200,
        msg: "获取用户成功",
        result
      })
    })
})


module.exports = router;
